import dayjs from "dayjs"
import { useServer } from "@/hooks/useServer"
const server = useServer()

/** 格式化时间 */
export const formatDateTime = (time: string | number | Date) => {
  return time ? dayjs(new Date(time)).format("YYYY-MM-DD HH:mm:ss") : "N/A"
}

/** 用 JS 获取全局 css 变量 */
export const getCssVariableValue = (cssVariableName: string) => {
  let cssVariableValue = ""
  try {
    // 没有拿到值时，会返回空串
    cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
  } catch (error) {
    console.error(error)
  }
  return cssVariableValue
}

/** 用 JS 设置全局 CSS 变量 */
export const setCssVariableValue = (cssVariableName: string, cssVariableValue: string) => {
  try {
    document.documentElement.style.setProperty(cssVariableName, cssVariableValue)
  } catch (error) {
    console.error(error)
  }
}

/** 手机号校验 */
export const checkPhone = (rule: any, value: string, callback: any) => {
  if (!value) return callback()
  // 手机号校验
  const regex = /^1[3|4|5|7|8]\d{9}$/
  const flag = regex.test(value)
  if (flag) {
    callback()
  } else {
    callback(new Error(""))
  }
}

/** 邮箱校验 */
export const checkEmail = (rule: any, value: string, callback: any) => {
  if (!value) return callback()

  // 邮箱校验
  const regex = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
  const flag = regex.test(value)
  if (flag) {
    callback()
  } else {
    callback(new Error(""))
  }
}

/** 密码输入 简单检验 */
export const simpleCheckPassword = (rule: any, value: string, callback: any) => {
  // 密码校验
  const regex = /^[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{6,16}$/
  const flag = regex.test(value)
  if (flag) {
    callback()
  } else {
    rule.message = "密码长度不得少于6位，由任意数字、字母、符号或其组合组成"
    callback(new Error(""))
  }
}

/** 密码输入 严格检验 */
export const strictCheckPassword = (rule: any, value: string, callback: any) => {
  // 密码校验
  const regex =
    /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/
  const flag = regex.test(value)
  console.info(flag)
  console.info(value)
  if (flag) {
    callback()
  } else {
    rule.message = "长度不得少于8位，由数字、大&小写字母、符号组成（至少4选3）"
    callback(new Error(""))
  }
}

/** 正则检验 不能包含空格+特殊字符 */
export const checkSpaceAndSpecialCharacters = (rule: any, value: string, callback: any) => {
  // 密码校验
  const regex = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/
  const flag = regex.test(value)
  if (flag) {
    callback()
  } else {
    rule.message = "不可输入空格和特殊字符"
    callback(new Error(""))
  }
}

/** 账号检验 */
export const checkAccount = (rule: any, value: string, callback: any) => {
  // 密码校验
  const regex = /^[a-zA-Z0-9_\u4e00-\u9fa5]{4,20}$/
  const flag = regex.test(value)
  if (flag) {
    callback()
  } else {
    rule.message = "账号4-20位，由数字、字母、下划线中的一种或多种组成，不区分大小写，不能输入空格或特殊字符"
    callback(new Error(""))
  }
}

/** 检验ipv4地址 */
export const isValidIPv4 = (ip: string) => {
  if (!ip) return true
  const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
  if (!ipv4Regex.test(ip)) {
    return false
  }
  const parts = ip.split(".").map(Number) as number[]
  return parts.every((part) => part >= 0 && part <= 255)
}

/** 检验端口号 不可以输入特殊字符和空格 */
export const isValidPort = (port: string) => {
  if (!port) return true
  const regex = /^[a-zA-Z0-9_\u4e00-\u9fa5]{4,20}$/
  const flag = regex.test(port)
  return flag
}

/** 随机生成一个clientId格式： 'pc-17位数' */
const hexList: string[] = []
for (let i = 0; i <= 15; i++) {
  hexList[i] = i.toString(16)
}

export function buildUUID(): string {
  let uuid = ""
  for (let i = 1; i <= 36; i++) {
    if (i === 9 || i === 14 || i === 19 || i === 24) {
      uuid += "-"
    } else if (i === 15) {
      uuid += 4
    } else if (i === 20) {
      uuid += hexList[(Math.random() * 4) | 8]
    } else {
      uuid += hexList[(Math.random() * 16) | 0]
    }
  }
  return uuid.replace(/-/g, "")
}

export function isUndef(val: any) {
  return typeof val === "undefined"
}

export function isNull(val: any) {
  return val === null
}

export function isNullOrUndef(val: any) {
  return isNull(val) || isUndef(val)
}

// 通过文件流下载文件
export const downloadByBlobUrl = (blob: Blob, name: string, type: string = "application/zip") => {
  const a = document.createElement("a")
  a.download = name
  a.href = URL.createObjectURL(new Blob([blob], { type }))
  a.click()
  document.body.appendChild(a)
  URL.revokeObjectURL(a.href)
  document.body.removeChild(a)
}

// 判断path是否以http/https开头 否则拼上当前域名
export const handleCheckPath = (url: string) => {
  // 正则校验是否以http https开头
  const regex = /^(http|https):\/\//
  const isValid = regex.test(url)
  if (isValid) {
    return url
  } else {
    return `${server}${url}`
  }
}
